package com.erp.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.shop.mapper.ErpSellerStoreFreightTemplateMapper;
import com.erp.shop.service.IErpSellerStoreFreightTemplateService;
import com.ruoyi.ae.api.RemoteAeProductService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.shop.api.domain.ErpSellerStoreFreightTemplate;
import com.ruoyi.shop.api.domain.bo.ErpSellerStoreFreightTemplateBo;
import com.ruoyi.shop.api.domain.vo.ErpSellerStoreFreightTemplateVo;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 店铺运费模板Service业务层处理
 *
 * @author erp
 * @date 2023-03-29
 */
@RequiredArgsConstructor
@Service
public class ErpSellerStoreFreightTemplateServiceImpl implements IErpSellerStoreFreightTemplateService {

    private final ErpSellerStoreFreightTemplateMapper baseMapper;
    @Resource
    RemoteAeProductService remoteAeProductService;

    /**
     * 查询店铺运费模板
     */
    @Override
    public ErpSellerStoreFreightTemplateVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询店铺运费模板列表
     */
    @Override
    public TableDataInfo<ErpSellerStoreFreightTemplateVo> queryPageList(ErpSellerStoreFreightTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSellerStoreFreightTemplate> lqw = buildQueryWrapper(bo);
        Page<ErpSellerStoreFreightTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询店铺运费模板列表
     */
    @Override
    public List<ErpSellerStoreFreightTemplateVo> queryList(ErpSellerStoreFreightTemplateBo bo) {
        LambdaQueryWrapper<ErpSellerStoreFreightTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSellerStoreFreightTemplate> buildQueryWrapper(ErpSellerStoreFreightTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerStoreFreightTemplate> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getSellerStoreId() != null, ErpSellerStoreFreightTemplate::getSellerStoreId, bo.getSellerStoreId());
        lqw.eq(bo.getTemplateId() != null, ErpSellerStoreFreightTemplate::getTemplateId, bo.getTemplateId());
        lqw.like(StringUtils.isNotBlank(bo.getTemplateName()), ErpSellerStoreFreightTemplate::getTemplateName, bo.getTemplateName());
        lqw.eq(StringUtils.isNotBlank(bo.getIsDefault()), ErpSellerStoreFreightTemplate::getIsDefault, bo.getIsDefault());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerStoreFreightTemplate::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增店铺运费模板
     */
    @Override
    public Boolean insertByBo(ErpSellerStoreFreightTemplateBo bo) {
        ErpSellerStoreFreightTemplate add = BeanUtil.toBean(bo, ErpSellerStoreFreightTemplate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改店铺运费模板
     */
    @Override
    public Boolean updateByBo(ErpSellerStoreFreightTemplateBo bo) {
        ErpSellerStoreFreightTemplate update = BeanUtil.toBean(bo, ErpSellerStoreFreightTemplate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerStoreFreightTemplate entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除店铺运费模板
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean addSellerTemplateList(List<ErpSellerStoreFreightTemplate> templateList, Long sellerId) {
        for (ErpSellerStoreFreightTemplate template : templateList) {
            template.setSellerStoreId(sellerId);
        }
        return baseMapper.insertBatch(templateList);
    }

    @Override
    public Integer deleteFreightTemplateBySellerId(Long sellerId) {
        return baseMapper.delete(new LambdaQueryWrapper<ErpSellerStoreFreightTemplate>().eq(ErpSellerStoreFreightTemplate::getSellerStoreId, sellerId));
    }

    @Override
    public R<Object> getFreightTemplateOneByStoreIdAndName(Long storeId, String mbName) {
        LambdaQueryWrapper<ErpSellerStoreFreightTemplate> freLqw = new LambdaQueryWrapper<ErpSellerStoreFreightTemplate>();
        freLqw.eq(ErpSellerStoreFreightTemplate::getSellerStoreId, storeId);
        freLqw.like(ErpSellerStoreFreightTemplate::getTemplateName, mbName);
        freLqw.last("limit 1");
        ErpSellerStoreFreightTemplate erpSellerStoreFreightTemplate = baseMapper.selectOne(freLqw);
        if (Objects.isNull(erpSellerStoreFreightTemplate)) {
            return R.fail(null);
        } else {
            return R.ok(erpSellerStoreFreightTemplate);
        }
    }

    @Override
    public R<Object> getFreightTemplateLogisticsCompany(Long templateId, String storeId) {
        Map<String, Object> paremeterMap = new HashMap<>();
        ErpSellerStoreFreightTemplate template = baseMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreFreightTemplate>()
                        .eq(ErpSellerStoreFreightTemplate::getTemplateId, templateId)
                        .eq(ErpSellerStoreFreightTemplate::getSellerStoreId, storeId)
        );
        if (template == null) {
            return R.fail("运费模板不存在");
        }
        paremeterMap.put("templateId", template.getTemplateId());
        paremeterMap.put("storeId", template.getSellerStoreId());
        R<Object> freightTemplateLogisticsCompany = remoteAeProductService.getFreightTemplateLogisticsCompany(template.getTemplateId(),template.getSellerStoreId());
        String returnStr = null;
        try {
           String body =  JSONObject.toJSONString(freightTemplateLogisticsCompany.getData());
           returnStr = JSONObject.parseObject(body).getString("data");
           System.out.println(returnStr);
           Integer code = JSONObject.parseObject(body).getInteger("code");
           if (code != 200) {
               return R.fail("获取运费模板异常");
           }
       }catch (Exception e){
           return R.fail("获取运费模板异常");
       }

        //该运费模板发货地
        List<String> logisticsCompanyList = Arrays.asList(returnStr.split(","));

        return R.ok(logisticsCompanyList);
    }

    @Override
    public R<Object> getSellerStoreFreightTemplate(Long sellerId) {
        //Ae接口
        R<Object> rreightTemplate = remoteAeProductService.getSellerStoreFreightTemplate(sellerId);
        String body = rreightTemplate.getData().toString();
        System.out.println(body);
        JSONObject returnObject = JSONObject.parseObject(body);
        if (returnObject == null)
            return R.ok("获取店铺运费模板失败");

        //保存该信息至店铺运费模板表
        deleteFreightTemplateBySellerId(sellerId);
        String jsonArray = returnObject
                .getJSONObject("aeop_freight_template_d_t_o_list")
                .getString("aeopfreighttemplatedtolist");
        //先删除该店铺所有的运费模板
        List<ErpSellerStoreFreightTemplate> templateList = JSONArray.parseArray(jsonArray, ErpSellerStoreFreightTemplate.class);
        if (addSellerTemplateList(templateList, sellerId)) {
            return R.ok("获取店铺运费模板成功");
        } else {
            return R.ok("获取店铺运费模板失败");
        }
    }
}
